package org.example.controller;

import org.example.entity.Worker;
import org.example.mapper.WorkerMapper;
import org.example.service.WorkerService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

@RequestMapping("test")
@RestController
public class TestController {

    @Resource
    private WorkerService workerService;

    @Resource
    private WorkerMapper workerMapper;

    @PostMapping("insert")
    public Integer saveEntity(){
        return workerService.saveEntity();
    }
    @PostMapping("batch")
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(){

        int[] ints = IntStream.rangeClosed(1, 10000).toArray();
        List<Worker> workers = Arrays.stream(ints).boxed().map(num -> {
            Worker worker = new Worker();
            worker.setName("孙悟空" + num);
            worker.setDoes("技术专家");
            worker.setScene(num % 2 == 0 ? "场景" + num : null);
            worker.setAge(100);
            return worker;
        }).collect(Collectors.toList());
       return workerService.saveBatch(workers);
    }


    @Transactional(rollbackFor = Exception.class)
    @PutMapping("batch")
    public Boolean updateBatch(){
        List<Worker> list = workerService.list();
        list.forEach(worker -> worker.setRemark("修改"));
        return workerService.updateBatchById(list);
    }

    @PutMapping("update")
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(){
        List<Worker> list = workerService.list();
        list.stream().findFirst().ifPresent(worker -> {
            worker.setRemark("单个修改");
            workerMapper.updateById(worker);
        });
        return Boolean.TRUE;
    }

    @DeleteMapping("batch")
    public Boolean batchDel(){
        return workerService.batchDel();
    }

    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("del")
    public Boolean del(){
        List<Worker> list = workerService.list();
        list.stream().findFirst().ifPresent(workerService::removeById);
        return Boolean.TRUE;
    }


}
